package logic

import (
	"book/bookrpc/bookrpc"
	"book/bookrpc/internal/svc"
	"book/models/mysql"
	"context"
	"fmt"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookShowLogic {
	return &BookShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookShowLogic) BookShow(in *bookrpc.BookShowRequest) (*bookrpc.BookShowResponse, error) {
	// todo: add your logic here and delete this line
	var book mysql.BookData
	mysql.DB.Debug().Model(&mysql.Book{}).
		Select("books.*, users.`name` as user_name, classes.`name` as class_name").
		Joins("LEFT JOIN users ON users.id = books.user_id").
		Joins("LEFT JOIN classes on classes.id = books.class_id").
		Where("books.id = ?", in.BookId).
		Find(&book)

	if book.ID == 0 {
		return nil, fmt.Errorf("当前图书不存在,请更换其他小说阅读")
	}

	m := mysql.Book{
		Model: gorm.Model{
			ID: uint(in.BookId),
		},
		BrowseNumber: book.BrowseNumber + 1,
	}

	mysql.DB.Debug().Updates(&m)

	return &bookrpc.BookShowResponse{
		UserName:     book.UserName,
		ClassName:    book.ClassName,
		Title:        book.Title,
		Image:        book.Image,
		Context:      book.Context,
		BookId:       int64(book.ID),
		BrowseNumber: book.BrowseNumber,
	}, nil
}
